<template>
    <div class="artifact-container">

        <el-card class="bread-card">
            <div slot="header" class="clearfix">
                <el-breadcrumb separator="/" class="artBread">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>文物管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>

           <el-form :inline="true" ref="searchForm" label-width="80px">
               <el-form-item>
                   <el-input v-model="searchArtName" size="small" placeholder="文物名"></el-input>
               </el-form-item>

               <el-form-item>
                   <el-select v-model="searchArtCate" placeholder="文物类别" size="small">
                       <el-option label="全部" value=""></el-option>
                       <el-option label="青铜器" value="1"></el-option>
                       <el-option label="玉石器" value="2"></el-option>
                       <el-option label="陶器" value="3"></el-option>
                   </el-select>
               </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="mini" @click="selectArtPage">
                        <i class="iconfont icon-search"></i>
                    </el-button>
                </el-form-item>
           </el-form>

            <div class="operaBtn">
                <el-button type="primary" size="mini" class="el-icon-plus" @click="addArtPre">新增</el-button>
                <el-button type="danger" size="mini" class="el-icon-delete" @click="handleDeleteList" :disabled="idlist.length == 0 ? true : false">删除</el-button>
            </div>

            <el-table :data="artArray" style="width: 100%" v-loading="loading" @selection-change="selectionChange">
                <el-table-column type="selection" width="85">
                </el-table-column>

                <el-table-column prop="title" label="文物名">
                </el-table-column>

                <el-table-column label="文物展示">
                    <template slot-scope="scope">
                        <el-image
                            style="width: 50px; height: 50px"
                            :src="scope.row.image"
                            fit="cover">
                        </el-image>
                    </template>
                </el-table-column>

                <el-table-column label="类别" width="180">
                    <template slot-scope="scope">
                        <span>{{scope.row.artcate.name}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleEditPre(scope.row,scope.$index)" type="primary" size="mini" class="el-icon-edit" >编辑</el-button>
                        <el-button @click="handleDelete(scope.row)" type="danger" size="mini" class="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 编辑文物的对话框start -->
            <el-dialog title="编辑文物" :visible.sync="editFormVisible" :before-close="cancleEdit">
                <el-form ref="editForm" :model="editArtForm" label-width="80px" label-position="left">
                    <el-form-item label="文物名">
                        <el-input v-model="editArtForm.title"></el-input>
                    </el-form-item>

                    <el-form-item label="介绍">
                        <!-- <vue-editor v-model="editArtForm.introduce" 
                                    useCustomImageHandler
                                    @image-added="handleImageAdded"
                        > -->
                        <quill-editor
                            class="editor"
                            ref="quillEditor"
                            v-model="editArtForm.introduce"
                            :options="editorOption"
                            @blur="onEditorBlur($event)"
                            @focus="onEditorFocus($event)"
                            @ready="onEditorReady($event)"
                        />   
                        <input type="file" @change="changeImage" id="upload" style="display:none;" />
                        <!-- <el-input type="textarea" v-model="editArtForm.introduce"></el-input> -->
                    </el-form-item>

                     <el-form-item label="展示">
                            
                            <!-- <el-dialog :visible.sync="bigImageVisible">
                                <img width="100%" :src="bigImageUrl" alt="">
                            </el-dialog> -->
                        <el-upload
                            :action="ImageUrl"
                            :headers="headers"
                            :on-remove="handleRemove"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            multiple
                            :limit="1"
                            :on-exceed="handleExceed"
                            :file-list="fileList"
                            list-type="picture-card"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>

                        
                    </el-form-item>

                    <el-form-item label="类别">
                        <el-select v-model="editArtForm.artcate.name" placeholder="选择分类">
                            <el-option label="青铜器" value="青铜器"></el-option>
                            <el-option label="玉石器" value="玉石器"></el-option>
                            <el-option label="陶器" value="陶器"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancleEdit">取消</el-button>
                    <el-button type="primary" @click="handleEdit" :loading="editLoading">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑文物的对话框end -->


            <!-- 新增文物的对话框start -->
            <el-dialog title="新增文物" :visible.sync="addFormVisible" :before-close="cancleAddArt">
                <el-form ref="editForm" :model="addArtForm" label-width="80px" label-position="left">
                    <el-form-item label="文物名">
                        <el-input v-model="addArtForm.title"></el-input>
                    </el-form-item>

                    <el-form-item label="介绍">
                        <quill-editor
                            class="editor"
                            ref="quillAddArt"
                            v-model="addArtForm.introduce"
                            :options="editorAddOption"
                            @blur="onEditorBlur($event)"
                            @focus="onEditorFocus($event)"
                            @ready="onEditorReady($event)"
                        />   
                        <input type="file" @change="changeAddImage" id="uploadAdd" style="display:none;" />
                    </el-form-item>

                     <el-form-item label="文物封面">
                        <el-upload
                            :action="ImageUrl"
                            :headers="headers"
                            :on-remove="handleRemove"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            multiple
                            :limit="1"
                            :on-exceed="handleExceed"
                            :file-list="fileList"
                            list-type="picture-card"
                        >
                            <i class="el-icon-plus"></i>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>

                        
                    </el-form-item>

                    <el-form-item label="类别">
                        <el-select v-model="addArtForm.artcate.name" placeholder="选择分类">
                            <el-option label="青铜器" value="青铜器"></el-option>
                            <el-option label="玉石器" value="玉石器"></el-option>
                            <el-option label="陶器" value="陶器"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancleAddArt">取消</el-button>
                    <el-button type="primary" @click="handleAddArt" :loading="addLoading">确定</el-button>
                </div>
            </el-dialog>
            <!-- 新增文物的对话框end -->

            <el-pagination
                class="pagination"
                background
                :current-page.sync="page"
                layout="prev, pager, next"
                :total="artCount"
                :page-size="5"
                @current-change="pageChange"
            >
            </el-pagination>

        </el-card>

    </div>
</template>

<script>
import { queryArtPage,updateArt,getArtCount,addArt,selectArtPage,deleteArt,deleteArtList } from '@/api/artifact'
import { uploadImg } from '@/api/uploadImage'
import { quillEditor, Quill } from 'vue-quill-editor'
import {container, ImageExtend} from 'quill-image-extend-module'
import ImageResize from "quill-image-resize-module"; // 引用
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册
Quill.register('modules/ImageExtend', ImageExtend)
export default {
    name: 'Artifact',
    components:{ 
        quillEditor
    },

    data() {
        let artcate = { 
            '青铜器':1,
            '玉石器':2,
            '陶器':3
        }
        const artcateMap = new Map(Object.entries(artcate))
        
        
        return {
            ImageUrl:this.baseURL+"/Image/upload",
            headers:{ 
                Authorization:"Bearer "+JSON.parse(window.localStorage.getItem("result")).token
            },
            quillId:'',
            searchArtName: '',
            searchArtCate: '',
            artArray:[],
            artcateMap,
            editIndex:0,//编辑item的索引
            page:1,//当前页码
            artCount:0,//文物总数
            editArtForm:{
                aid:null, 
                title:null,//文物名
                introduce:null,//介绍
                image: '',
                artcate:{ 
                    acid:null,
                    name:null
                }
            },
            editFormVisible:false,
            loading:false,//加载效果开启与关闭
            addArtForm:{ },//新增文物
            addFormVisible:false,//新增文物的对话框的关闭与开启
            addLoading:false,
            editLoading:false,
            idlist:[],//要删除的文物id列表
            fileList:[],
            editorOption: {
                placeholder: '请输入文本...',
                theme: 'snow',
                modules: {

                    imageDrop: true, //图片拖拽
                    imageResize: {
                        displaySize: true
                    },

                    toolbar: {
                        container:container,
                        
                        handlers: {
                            image: function(value) {
                                if (value) {
                                    document.querySelector("#upload").click()  // 劫持原来的图片点击按钮事件
                                    
                                } else {
                                    this.quill.format('image', false)
                                }
                            }
                        }
                    }
                },
            },

            editorAddOption: {
                placeholder: '请输入文本...',
                theme: 'snow',
                modules: {

                    imageDrop: true, //图片拖拽
                    imageResize: {
                        displaySize: true
                    },

                    toolbar: {
                        container:container,
                        
                        handlers: {
                            image: function(value) {
                                if (value) {
                                    document.querySelector("#uploadAdd").click()  // 劫持原来的图片点击按钮事件
                                    
                                } else {
                                    this.quill.format('image', false)
                                }
                            }
                        }
                    }
                },
            },

            bigImageVisible:false,
            disabled:false
        };
    },

    created() { 
        this.addArtForm = { 
            ...this.editArtForm,
            artcate:{ 
                ...this.editArtForm.artcate
            }
        }
    },

    mounted() {
        /**
         * 查询分页数据
         */
        this.queryArtPage()
        this.getArtCount()

    },

    methods: {

        /**
         * 打开编辑框
         */
        handleEditPre(artifact,index){
            this.editIndex = index
            console.log("index = ",index)
            console.log("artifact",artifact)


            //对象深拷贝(一)
            // this.editArtForm = JSON.parse(JSON.stringify(artifact))

            //对象深拷贝(二)
            this.editArtForm = { 
                ...artifact,
                artcate:{ 
                    ...artifact.artcate
                }
            }

            let file = { 
                name:this.editArtForm.image,
                url: this.editArtForm.image
            }

            this.fileList.push(file)
            this.fileList = this.fileList.splice(-1)

            console.log("editArtForm",this.editArtForm)
            this.editFormVisible = true

        },
        
        /**
         * 更新文物记录
         */
        handleEdit(){ 
            console.log("map = ",this.artcateMap)
            this.editArtForm.artcate.acid = this.artcateMap.get(this.editArtForm.artcate.name)
            
            let data = this.editArtForm

            data.image = this.fileList[0].name
            this.editLoading = true
            

            updateArt(data).then(res => { 
                if(res.data == 1){ 
                    this.editFormVisible = false
                    console.log("this.index",this.editIndex)
                    this.artArray.splice(this.editIndex,1,data)
                    //更新文物数组


                    this.editLoading = false
                    this.$message({ 
                        type:'success',
                        message:'编辑成功'
                    })
                    this.fileList.splice(0)

                    
                } else { 
                    this.$message({ 
                        type:'error',
                        message:'编辑失败，请重试'
                    })

                    this.editLoading = false
                }
            }).catch(err => {
                this.$message({ 
                    type:'error',
                    message:'编辑失败，请重试'
                })
            })
        },

        /**
         * 取消编辑操作
         */
        cancleEdit(){ 
            this.editFormVisible = false

            this.clearForm(this.editArtForm)

            this.fileList.pop()

            console.log("已取消编辑操作",this.editArtForm)
        },


        /**
         * 清空表单对象的属性值
         */
        clearForm(obj){ 
            Object.keys(obj).forEach(key => {obj[key] = null})
            let artcate = { 
                acid:null,
                name:null
            }

            obj.artcate = { 
                ...artcate
            }
        },


        /**
         * 处理删除操作
         */
        handleDelete(artifact) { 
            this.$confirm('你确定要删除吗？','提示',{ 
                confirmButtonText:'确定',
                cancleButtonText:'取消',
                type:'warning'
            }).then(() => { 
                this.deleteArt(artifact.aid)
            }).catch(() => { 
                this.$message({ 
                    type:"info",
                    message:'取消删除'
                })
            })
        },

        /**
         * 删除文物
         */
        deleteArt(artId) { 
            let params = { 
                artId: artId
            }

            deleteArt(params).then(res => {
                /**
                 * 删除成功则执行以下操作
                 * 1.重新查询总页码数---总数量%5做判断
                 * 2.查询后，如果说当前页码不是1，并且正好大于新的页码总数，则将其减一
                 * 3.然后执行查询分页数据的操作
                 */
                this.getArtCount().then(() => {
                    console.log("this",this)
                    console.log("pageCount",this.artCount)
                    let newPageCount = this.artCount % 5 == 0 ? this.artCount / 5 : this.artCount / 5 + 1
                    let page = this.page != 1 && this.page > newPageCount ? page - 1 : this.page
                    this.page = page
                    this.pageChange()
                    this.$message({ 
                        type:"success",
                        message:'删除成功'
                    })
                })

               
                
            }).catch(err => { 
                this.$message({ 
                        type:"error",
                        message:'删除失败'
                    })
            })

        },

        /**
         * 文件移除操作
         */
        handleRemove(file, fileList){ 
            this.fileList.pop()
            this.$message({ 
                type:'success',
                message:'文件移除成功'
            })
            console.log("文件移除",file,fileList)
        },

        /**
         * 文件上传成功
         */
        handleUploadSuccess(response, file, fileList){
            let fileItem = { 
                name:response,
                url:response
            }

            this.fileList.push(fileItem)
            this.fileList = this.fileList.splice(-1)

            this.$message({ 
                type:'success',
                message:'上传成功'
            })

            console.log("上传成功")
            console.log("res = ",response)
            console.log("file = ",file)
            console.log("fileList = ",fileList)
        },

        /**
         * 文件上传失败
         */
        handleUploadError(err, file, fileList){ 
            this.$message({ 
                type:'error',
                message:'上传文件失败'
            })

            console.log("上传失败")
            console.log("error = ",err)
            console.log("file = ",file)
            console.log("fileList = ",fileList)
        },

        /**
         * 文件数量超出限制
         * 让其在更新文件时执行
         */
        handleExceed(files, fileList){
            console.log("超出文件限制")
            console.log("file = ",files)
            console.log("fileList",fileList)

            if(files.length == 1){ 

                let data = new FormData()
                data.append("file",files[0])

                //发送图片上传请求
                uploadImg(data).then(res => { 
                    let fileItem = { 
                        name:res.data,
                        url:res.data
                    }

                    this.fileList.push(fileItem)
                    this.fileList = this.fileList.splice(-1)
                    console.log("超出文件请求上传成功",res)
                }).catch(err => { 
                    console.log("超出文件请求上传失败",err)
                    this.$message({ 
                        type:'error',
                        message:'更新文件失败'
                    })
                })

            } else { 
                this.$message({ 
                    type:'warning',
                    message:'只能选择一张图片'
                })
            }

            
        },

        onEditorBlur(quill) {
            console.log('editor blur!', quill)
        },
        //获得焦点事件
        onEditorFocus(quill) {
            console.log('editor focus!', quill)
        },
        // 准备富文本编辑器
        onEditorReady(quill) {
            console.log('editor ready!', quill)
        },

        /**
         * 当富文本编辑器选中图片后执行上传图片操作
         */
        changeImage(e){ 
            console.log("quill",this.$refs.quillEditor.quill)
            console.log("quill上传文件",e)

            let file = e.target.files[0]
            const formData = new FormData()
            formData.append('file', file)

            uploadImg(formData).then(res => {
                console.log("quill上传成功！！！！") 
                let quill = this.$refs.quillEditor.quill
                let length = quill.getSelection().index
                console.log("光标位置",length)

                let fileUrl = res.data
                quill.insertEmbed(length, 'image', fileUrl)
                quill.setSelection(length + 1)//光标后移一位

            }).catch(err => {

            })

        },

        /**
         * 查询分页数据
         */
        queryArtPage() { 
            this.loading = true
            let params = { 
                page:this.page
            }

            queryArtPage(params).then(res => { 
                this.artArray = res.data
                this.loading = false

            }).catch(err => { 
                console.log(err)
                this.loading = false
                this.$message({ 
                    type:danger,
                    message:'加载失败'
                })
            })
        },


        /**
         * 按文物名，分类查询分页数据
         */
        selectArtPage(){ 
            this.page = 1
            this.loading = true
            let params = { 
                page:this.page,
                artId:this.searchArtCate,
                artName:this.searchArtName
            }

            selectArtPage(params).then(res => { 
                this.artArray = res.data
                console.log(res.data)
                this.loading = false
                this.getArtCount()

            }).catch(err => { 
                console.log(err)
                this.loading = false
                this.$message({ 
                    type:danger,
                    message:'加载失败'
                })
            })
        },

        /**
         * 查询文物总数
         */
        getArtCount(){ 
    
            return new Promise((resolve,reject) => { 
                let params = { 
                    artId:this.searchArtCate,
                    artName:this.searchArtName
                }

                getArtCount(params).then(res => { 
                    this.artCount = res.data
                    resolve(res)
                }).catch(err => { 
                    console.log(err)
                    reject(new Error(err.statusText))
                })
            })
        },

        /**
         * 打开添加操作的对话框
         */
        addArtPre() { 
            this.addFormVisible = true
        },

        /**
         * 新增的对话框中富文本图片拦截
         */
        changeAddImage(e){ 

            let file = e.target.files[0]
            const formData = new FormData()
            formData.append('file', file)

            uploadImg(formData).then(res => {
                let quill = this.$refs.quillAddArt.quill
                let length = quill.getSelection().index

                let fileUrl = res.data
                quill.insertEmbed(length, 'image', fileUrl)
                quill.setSelection(length + 1)//光标后移一位

            }).catch(err => {

            })

        },


        /**
         * 新增文物操作
         */
        handleAddArt(){ 
            this.addArtForm.artcate.acid = this.artcateMap.get(this.addArtForm.artcate.name)
            this.addArtForm.image = this.fileList[0] == null ? "" : this.fileList[0].name

            this.addLoading = true

            addArt(this.addArtForm).then(res => { 
                this.$message({ 
                    type:'success',
                    message:'增加文物成功'
                })
                console.log("新增res = ",res)


                //重新查询分页数据
                this.queryArtPage()
                //更新总数
                this.getArtCount()


                this.addLoading = false
                //关闭对话框
                this.cancleAddArt()


            }).catch(err => {
                this.$message({ 
                    type:'error',
                    message:'增加文物失败'
                })

                this.addLoading = false
            })
        },

        cancleAddArt(){ 
            this.addFormVisible = false
            this.clearForm(this.addArtForm)
        },


        /**
         * 更新this.idlist
         */
        selectionChange(idlist) { 
            /**
             * 清空this.idlist数组
             * 1.调用splice
             * 2.直接置length=0
             */
            // this.idlist.splice(0)

            /**
             * this.idlist.length = 0 也可以清空数组
             * 但是vue监测不到
             * vue内部清空数组使用的此种方法
             */
        //    idlist.forEach(item => { 
        //        this.idlist.push(item.aid)
        //    })
            /**
             * 上述是一种更新数组的方法，这里我们使用扩展运算符直接拷贝数组
             */
            this.idlist = [...idlist]

           console.log("this.idlist",this.idlist)
        },

        handleDeleteList(){ 
            this.$confirm('你确定要删除吗？','提示',{ 
                confirmButtonText:'确定',
                cancleButtonText:'取消',
                type:'warning'
            }).then(() => { 
                this.deleteArtList()
            }).catch(() => { 
                this.$message({ 
                    type:"info",
                    message:'取消删除'
                })
            })
        },

        /**
         * 删除文物列表
         */
        deleteArtList(){ 
            let idList = ""
            this.idlist.forEach(item => {
                idList += item.aid + ","
            });

            let params = { 
                'idList':idList
            }


            deleteArtList(params).then(res => {
                /**
                 * 删除成功要做以下几件事
                 * 1.重新更新总页码数---查询文物总数量 % 5==0 ?  总数 /5 :总数 / 5 + 1
                 * 2.判断：如果当前页码比更新后的总页码数还要大，则将其减一，否则不变
                 * 3.查询文物---带条件
                 */
                this.getArtCount().then(() => {
                    
                    let newPageCount = this.artCount % 5 == 0 ? this.artCount / 5 : this.artCount / 5 + 1
                    let page = this.page != 1 && this.page > newPageCount ? page - 1 : this.page
                    this.page = page
                    this.pageChange()
                    this.$message({ 
                        type:"success",
                        message:'删除成功'
                    })
                })


            }).catch(err => { 

            })
        },

        /**
         * 点击分页页码触发
         */
        pageChange(){ 
            console.log("分页")
            this.loading = true
            let params = { 
                page:this.page,
                artId:this.searchArtCate,
                artName:this.searchArtName
            }

            selectArtPage(params).then(res => { 
                this.artArray = res.data
                console.log(res.data)
                this.loading = false
                this.getArtCount()

            }).catch(err => { 
                console.log(err)
                this.loading = false
                this.$message({ 
                    type:danger,
                    message:'加载失败'
                })
            })
        }
        

       


    },
};
</script>

<style scoped>

.artifact-container
{
    margin: 20px 30px;
    min-width: 1275px;
}

.pagination{ 
    margin-top: 30px;
}

</style>